package com.yaodian100.ec.activity.service.impl;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.util.ArrayList;
import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.transaction.annotation.Transactional;

import com.yaodian100.core.common.dao.impl.CommonCriteria;
import com.yaodian100.core.common.exception.CoreException;
import com.yaodian100.core.common.service.impl.DomainServiceImpl;
import com.yaodian100.core.common.utils.ServerValue;
import com.yaodian100.ec.activity.entity.ActivityPageBlock;
import com.yaodian100.ec.activity.entity.ActivityPageBlockBanner;
import com.yaodian100.ec.activity.entity.ActivityPageBlockProduct;
import com.yaodian100.ec.activity.service.ActivityPageBlockBannerService;
import com.yaodian100.ec.activity.service.ActivityPageBlockService;
import com.yaodian100.ec.shelf.entity.ViewShelf;
import com.yaodian100.ec.shelf.service.ShelfService;

public class ActivityPageBlockServiceImpl extends DomainServiceImpl<ActivityPageBlock> implements ActivityPageBlockService {

	@Autowired
	private JdbcTemplate jdbcTemplate;
	
	@Autowired
	private ShelfService shelfService;
	
	@Autowired
	private ActivityPageBlockBannerService activityPageBlockBannerService;
	
	@Override
	@Transactional(readOnly=false)
	public void saveWithOrder(ActivityPageBlock block) throws CoreException {
		CommonCriteria criteria = new CommonCriteria();
		criteria.addEq("pageId", block.getPageId());
		long current = super.getDao().getListSize(criteria).longValue();
		block.setSortOrder(current+1);
		super.save(block);
	}

	private void removeUploadBannerImages(long blockId) {
		try {
			String dir = BANNER_IMAGE_PATH + "/" + String.valueOf(blockId);
			File file = new File(dir);
			for (File f:file.listFiles()) {
				f.delete();
			}
			file.delete();
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
	
	@Override
	@Transactional(readOnly=false)
	public void delBlockResetOrder(long id) throws CoreException {
		ActivityPageBlock block = super.get(id);
		if (block == null) return;
		this.resetOrder(block.getPageId(),block.getSortOrder());
		super.delete(block);
		removeUploadBannerImages(block.getId());
	}
	
	private void resetOrder(long pageId,Long baseOrder) throws CoreException {
		StringBuffer sql = new StringBuffer();
		sql.append("UPDATE EC_ACTIVITY_PAGE_BLOCK SET SORT_ORDER = SORT_ORDER - 1 WHERE PAGE_ID = ").append(pageId);
		if (baseOrder != null) {
			sql.append(" AND SORT_ORDER > ").append(baseOrder);
		}
		this.jdbcTemplate.execute(sql.toString());
	}

	public JdbcTemplate getJdbcTemplate() {
		return jdbcTemplate;
	}

	public void setJdbcTemplate(JdbcTemplate jdbcTemplate) {
		this.jdbcTemplate = jdbcTemplate;
	}

	@Override
	@Transactional(readOnly=false)
	public boolean switchBlockSortOrder(long fromId, long toId) throws CoreException {
		ActivityPageBlock fromBlock = super.get(fromId);
		ActivityPageBlock toBlock = super.get(toId);
		if (fromBlock == null || toBlock == null) return false;
		long fromOrder = fromBlock.getSortOrder();
		long toOrder = toBlock.getSortOrder();
		
		fromBlock.setSortOrder(toOrder);
		toBlock.setSortOrder(fromOrder);
		
		super.update(fromBlock);
		super.update(toBlock);
		
		return true;
	}

	

	public ShelfService getShelfService() {
		return shelfService;
	}

	public void setShelfService(ShelfService shelfService) {
		this.shelfService = shelfService;
	}

	@Override
	public List<String> getValidShelfProducts(List<ActivityPageBlockProduct> products) throws CoreException {
		List<String> pids = new ArrayList<String>();
		List<String> result = new ArrayList<String>();
		for (ActivityPageBlockProduct product:products) {
			if (product.getProductId() != null && product.getProductId().length() > 0)
			pids.add(product.getProductId());
		}
		if (pids.size() == 0) return result;
		
		List<ViewShelf> viewShelfList = this.shelfService.getPublishShelfs(null, pids.toArray(new String[0]));
		for (ViewShelf shelf : viewShelfList) {
			result.add(shelf.getProductId());
		}
		return result;
	}

	@Override
	@Transactional(readOnly=false)
	public ActivityPageBlock saveBlockBanners(ActivityPageBlock block) throws CoreException {
		try {
			ActivityPageBlock pageBlock = this.get(block.getId());
			
			pageBlock.getBanners().clear();
			
			String dir = BANNER_IMAGE_PATH + "/" + pageBlock.getId();
			for (int i=0;i<block.getBanners().size();i++) {
				ActivityPageBlockBanner banner = block.getBanners().get(i);
				ActivityPageBlockBanner blockBanner;
				
				if (banner.getId() != null) {
					blockBanner = this.activityPageBlockBannerService.get(banner.getId());
				} else {
					blockBanner = banner;
				}
				
				String filename = null;
				if (banner.getBannerImage() != null) {
					filename = getImageFileName(banner.getBannerImageFileName(),i+1);
					blockBanner.setImagePath(ServerValue.getFrontHostname() + BANNER_IMAGE_WEB_PATH + "/" + block.getId() + "/" + filename);
				}
				blockBanner.setTargetUrl(banner.getTargetUrl());
				blockBanner.setItemNo(Long.valueOf(i+1));
				blockBanner = this.activityPageBlockBannerService.save(blockBanner);
				pageBlock.getBanners().add(blockBanner);
				
				//上傳檔案
				if (banner.getBannerImage() != null) {
					File target = new File(dir,filename);
					target.getParentFile().mkdirs();
					FileOutputStream out = null;
					FileInputStream in = null;
					try {
						out = new FileOutputStream(target);
						in = new FileInputStream(banner.getBannerImage());
						byte[] b = new byte[256];
						while (in.read(b) != -1) {
							out.write(b);
						}
					} catch (Exception e) {
						e.printStackTrace();
						throw new CoreException("ActivityPageBlockService:"+e.getMessage(),e);
					} finally {
						try {
							in.close();
						} catch (Exception e) {}
						try {
							out.close();
						} catch (Exception e) {}
					}
				}
				banner.setBannerImage(null);
			}
			
			return pageBlock;
		} catch (Exception e) {
			e.printStackTrace();
			throw new CoreException(e.getMessage());
		}
	}
	
	private String getImageFileName(String filename,int itemNo) {
		int index = filename.lastIndexOf(".");
		String ext = filename.substring(index);
		return String.valueOf(itemNo) + ext;
	}

	@Override
	@Transactional(readOnly=false)
	public void updateBlockOrder(String[] blocks) throws CoreException {
		for (int i=0;i<blocks.length;i++) {
			long blockId = Long.parseLong(blocks[i]);
			ActivityPageBlock pageBlock = super.get(blockId);
			pageBlock.setSortOrder((long)(i+1));
			super.save(pageBlock);
		}
	}
	
	

}
